package cn.lonecloud.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.lonecloud.dao.ProductDao;
import cn.lonecloud.model.Product;
import cn.lonecloud.util.DBUtils;

/**
 * 商品实现层
 * @author  lonecloud
 */
public class ProductDaoImpl implements ProductDao {

	String tableName = "t_product";
	/**
	 * 
	 */
	private static final long serialVersionUID = -3969520730043246107L;

	@Override
	public Product save(Product entity) {
		String sql = "insert into " + tableName + "(name,description,count,updataTime,ownId)" + "values(?,?,?,?,?)";
		DBUtils.execute(sql, entity.getName(), entity.getDescription(), entity.getCount(), new Date(),
				entity.getOwn().getId());
		return entity;
	}

	@Override
	public void update(Product entity) {
		String sql = "UPDATE " + tableName + " set name=?,description=?,count=?,updataTime=?  where id=?";
		DBUtils.execute(sql, entity.getName(), entity.getDescription(), entity.getCount(), new Date(), entity.getId());
	}

	@Override
	public void deleteById(int id) {

	}

	@Override
	public Product findById(int id) {
		String sql = "select id,name,description,count,updataTime,ownId from " + tableName + " where id= ?";
		ResultSet resultSet = DBUtils.Query(sql, id);
		return transferObj(resultSet);
	}

	@Override
	public List<Product> findAll() {
		List<Product> products = new ArrayList<>();
		String sql = "select id,name,description,count,updataTime,ownId from " + tableName;
		ResultSet resultSet = DBUtils.Query(sql);
		Product product = null;
		while (true) {
			product = this.transferObj(resultSet);
			if (product != null) {
				products.add(product);
			} else {
				break;
			}
		}
		return products;
	}

	private Product transferObj(ResultSet resultSet) {
		Product product = null;
		try {
			if (resultSet != null && resultSet.next()) {
				product = new Product();
				product.setId(resultSet.getInt("id"));
				product.setName(resultSet.getString("name"));
				product.setDescription(resultSet.getString("description"));
				product.setCount(resultSet.getInt("count"));
				product.setUpdataTime(resultSet.getDate("updataTime"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return product;
	}

}
